<template>
  <div class="file-tree">
    <div class="tree-header">
      <div class="header-actions">
        <el-button-group>
          <el-button
            type="primary"
            size="small"
            :icon="FolderAdd"
            @click="createFolder"
            title="添加文件夹"
          />
          <el-button
            type="primary"
            size="small"
            :icon="DocumentAdd"
            @click="createNote"
            title="新建笔记"
          />
          <el-button
            type="primary"
            size="small"
            :icon="Search"
            @click="showSearch = !showSearch"
          />
          <el-button
            type="primary"
            size="small"
            :icon="Refresh"
            @click="refreshTree"
            title="刷新"
          />
        </el-button-group>
      </div>
    </div>

    <!-- 搜索框 -->
    <div v-if="showSearch" class="search-box">
      <el-input
        placeholder="搜索笔记..."
        v-model="searchQuery"
        clearable>
        <template #prefix>
          <el-icon>
            <Search/>
          </el-icon>
        </template>
      </el-input>
    </div>

    <div class="tree-content" @contextmenu.prevent="(e) => handleNodeContextmenu(e, rootNode)">
      <el-tree
        ref="treeRef"
        :props="defaultProps"
        expand-on-click-node
        node-key="id"
        highlight-current
        draggable
        check-on-click-node
        lazy
        icon="ArrowRight"
        :load="loadChildren"
        :filter-node-method="filterNode"
        :default-expanded-keys="defaultExpands"
        :allow-drop="allowDrop"
        :allow-drag="allowDrag"
        @node-click="handleNodeClick"
        @node-drop="handleDrop"
        @node-contextmenu="handleNodeContextmenu"
      >
        <template #default="{ node, data }">
          <div class="tree-node">
            <el-icon :size="16" class="node-icon">
              <component :is="getNodeIcon(data, node)"/>
            </el-icon>
            <span class="node-label">{{ data.item.title }}</span>
          </div>
        </template>
      </el-tree>
    </div>

    <!-- 历史记录查看器 -->
    <history-viewer
      v-model="showHistory"
      :note-id="selectedNoteId"
    />

    <!-- 重命名对话框 -->
    <!--    <el-dialog-->
    <!--      v-model="showMoveDialog"-->
    <!--      title="移动笔记"-->
    <!--      width="30%"-->
    <!--    >-->
    <!--      <div class="move-dialog-content">-->
    <!--        <el-tree-->
    <!--          :data="folderTreeData"-->
    <!--          :props="defaultProps"-->
    <!--          node-key="id"-->
    <!--          highlight-current-->
    <!--          :expand-on-click-node="false"-->
    <!--          @node-click="handleFolderSelect"-->
    <!--        >-->
    <!--          <template #default="{ node, data }">-->
    <!--            <div class="tree-node">-->
    <!--              <el-icon :size="16">-->
    <!--                <Folder/>-->
    <!--              </el-icon>-->
    <!--              <span class="node-label">{{ data.title || data.name }}</span>-->
    <!--            </div>-->
    <!--          </template>-->
    <!--        </el-tree>-->
    <!--      </div>-->
    <!--      <template #footer>-->
    <!--        <span class="dialog-footer">-->
    <!--          <el-button @click="showMoveDialog = false">取消</el-button>-->
    <!--          <el-button type="primary" @click="handleMoveConfirm">确认</el-button>-->
    <!--        </span>-->
    <!--      </template>-->
    <!--    </el-dialog>-->
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref} from 'vue'
import {ElMessage, ElMessageBox, ElTree} from 'element-plus'
import {Document, DocumentAdd, Folder, FolderAdd, FolderOpened, More, Refresh, Search} from '@element-plus/icons-vue'
import type {TreeNode} from '@/types'
import HistoryViewer from '../editor/HistoryViewer.vue'
import {useDirectoryStore} from "@/stores/directory.ts";
import {DirectoryTreeNode} from "../../../filespace/src";
import type Node from 'element-plus/es/components/tree/src/model/node'

const directoryStore = useDirectoryStore()

const treeRef = ref<InstanceType<typeof ElTree>>()
const showHistory = ref(false)
const showMoveDialog = ref(false)
const selectedNoteId = ref('')
const selectedTargetFolder = ref<TreeNode | null>(null)
const showSearch = ref(false)
const searchQuery = ref('')
const defaultExpands = ref<string[]>([])
window.bnote.dirs.openedIds().then(res => {
  defaultExpands.value = res
})
const rootNode = ref<DirectoryTreeNode>({} as DirectoryTreeNode)

// 加载子节点
const loadChildren = async (node: Node, resolve: (data: DirectoryTreeNode[]) => void) => {
  if (node.level === 0) {
    const root = await window.bnote.dirs.root()
    if (root) {
      const roots = root.children
      rootNode.value = root
      return resolve(roots || [])
    }
    return resolve([])
  }
  const children = await window.bnote.dirs.treeLazy(node.data.id)
  console.log(children)
  resolve((children?.children) || [])
}
//
// // 仅包含文件夹的树形数据
// const folderTreeData = computed(() => {
//   const folders = folderStore.folders
//
//   const buildTree = (parentId: string | null = null): TreeNode[] => {
//     return folders
//       .filter(f => f.parent === parentId)
//       .map(folder => ({
//         id: folder.id,
//         name: folder.name,
//         isFolder: true,
//         children: buildTree(folder.id)
//       }))
//   }
//
//   return [
//     {
//       id: 'root',
//       name: '根目录',
//       isFolder: true,
//       children: buildTree(null)
//     }
//   ]
// })

// 树形配置
const defaultProps = {
  children: 'children',
  label: 'item.title',
  isLeaf: (data: DirectoryTreeNode) => {
    return data && data.item && !data.item.isDirectory
  }
}

// 获取节点图标
const getNodeIcon = (data: DirectoryTreeNode, node: any) => {
  if (data.item.isDirectory) {
    return node.expanded ? FolderOpened : Folder
  }
  return Document
}

watch(searchQuery, (query) => {
  treeRef.value.filter(query)
})

const filterNode = (query: string, node: DirectoryTreeNode) => {
  const label = node.item.title
  return label.includes(query)
}

const handleNodeContextmenu = (event: any, data: DirectoryTreeNode) => {
  if (data.item.isDirectory) {
    window.bnote.contextmenus.noteDirs(JSON.parse(JSON.stringify(data)))
  } else {
    window.bnote.contextmenus.noteFiles(JSON.parse(JSON.stringify(data)))
  }
}

window.bnote.contextmenus.onNoteDirs((command: ContextmenusNoteDirsCommand, item: DirectoryTreeNode) => {
  if (command === 'new-dir') {
    ElMessageBox.prompt('请输入文件夹名称', '新建文件夹', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: (value) => {
        if (!value) {
          return '文件夹名称不能为空'
        }
        if (value.includes('/') || value.includes('\\')) {
          return '文件夹名称不能包含斜杠'
        }
        return true
      }
    }).then(({value}) => {
      if (value) {
        window.bnote.dirs.create(value, item.item.id).then((res) => {
          if (res.success) {
            ElMessage.success('创建成功')
            window.bnote.dirs.build(item.item.relativePath, {
              recursive: false,
              includeFiles: true,
              startFromPath: true
            }).then(bRes => {
              if (bRes) {
                treeRef.value?.updateKeyChildren(item.id, bRes.children || [])
              }
            })
          } else {
            ElMessage.error(res.error || '创建失败')
          }
        })
      }
    }).catch(() => {
      // 用户取消操作
    })
  } else if (command === 'new-note') {
    ElMessageBox.prompt('请输入笔记名称', '新建笔记', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: (value) => {
        if (!value) {
          return '笔记名称不能为空'
        }
        if (value.includes('/') || value.includes('\\')) {
          return '笔记名称不能包含斜杠'
        }
        return true
      }
    }).then(({value}) => {
      if (value) {
        window.bnote.files.create(value, '', item.item.id).then((res) => {
          if (res.success) {
            ElMessage.success('创建成功')
            window.bnote.dirs.build(item.item.relativePath, {
              recursive: false,
              includeFiles: true,
              startFromPath: true
            }).then(bRes => {
              if (bRes) {
                treeRef.value?.updateKeyChildren(item.id, bRes.children || [])
              }
            })
          } else {
            ElMessage.error(res.error || '创建失败')
          }
        })
      }
    }).catch(() => {
      // 用户取消操作
    })
  }
})

// 处理下拉菜单命令
const handleCommand = async (command: string, data: TreeNode) => {
  switch (command) {
    case 'rename':
      handleRename(data)
      break
    case 'move':
      handleMove(data)
      break
    case 'history':
      handleHistory(data)
      break
    case 'delete':
      handleDelete(data)
      break
  }
}

// 允许拖拽的条件
const allowDrag = (node: any) => {
  // 只允许拖拽笔记，不允许拖拽文件夹
  return !node.data.isFolder
}

// 允许放置的条件
const allowDrop = (draggingNode: any, dropNode: any, type: 'prev' | 'next' | 'inner') => {
  // 只允许放置到文件夹内
  if (type === 'inner') {
    return dropNode.data.isFolder
  }
  // 允许放置到同级
  return dropNode.parent.data.isFolder
}

// 处理拖拽放置
const handleDrop = async (draggingNode: any, dropNode: any, type: 'prev' | 'next' | 'inner') => {

}

// 检查文件夹是否为空
const isFolderEmpty = (folder: TreeNode): boolean => {
  return !folder.children || folder.children.length === 0
}

// 重命名处理
const handleRename = async (data: TreeNode) => {

}

// 删除处理
const handleDelete = async (data: TreeNode) => {

}

// 移动笔记
const handleMove = (data: TreeNode) => {
  selectedNoteId.value = data.id
  showMoveDialog.value = true
}

// 查看历史记录
const handleHistory = (data: TreeNode) => {
  selectedNoteId.value = data.id
  showHistory.value = true
}

const handleNodeClick = (data: any) => {
  // 添加或移除打开列表
  window.bnote.files.addOrRemoveOpen(data.item.id)
}

// 选择目标文件夹
const handleFolderSelect = (data: TreeNode) => {
  selectedTargetFolder.value = data
}

// 确认移动笔记
const handleMoveConfirm = async () => {

}

const createFolder = () => {

}

// 创建新笔记
const createNote = () => {

}

// 刷新文件树
const refreshTree = async () => {
  await Promise.all([
    directoryStore.loadFolders()
  ])
}

// 组件挂载时刷新文件树
onMounted(() => {
  refreshTree()
})
</script>

<style lang="scss" scoped>
.file-tree {
  height: 100%;
  display: flex;
  flex-direction: column;

  .tree-header {
    flex-shrink: 0;
    padding: 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid var(--el-border-color-light);

    .header-title {
      font-size: 16px;
      font-weight: bold;
    }
  }

  .tree-content {
    flex: 1;
    overflow: auto;

    //:deep(.el-tree-node__content) {
    //  height: 32px;
    //}
    //
    //:deep(.el-tree-node .el-tree-node__expand-icon) {
    //  display: none;
    //}
    //
    //:deep(.el-tree-node .el-tree-node__loading-icon) {
    //  display: none;
    //}
  }
}

.tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 0 12px 0 0;

  .node-icon {
    margin-right: 8px;
    color: var(--el-text-color-secondary);
  }

  .node-label {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .node-actions {
    display: none;
    margin-left: 8px;

    .el-icon {
      cursor: pointer;
      color: var(--el-text-color-secondary);

      &:hover {
        color: var(--el-color-primary);
      }
    }
  }

  &:hover .node-actions {
    display: block;
  }
}

.move-dialog-content {
  height: 300px;
  overflow: auto;
}

.search-box {
  padding: 8px 12px;
  border-bottom: 1px solid var(--el-border-color-light);
}
</style>
